var mongo = require('./db/db.js')
var tushare = require('./tushare/tushare.js')
const fastify = require('fastify')({ logger: false })
const serveStatic = require('serve-static')
const path = require('path')
var cfg  = require('./cfg/cfg.js')
var conv = require('./tushare/conv.js')

fastify.use('/', serveStatic(path.resolve(__dirname, 'web')))

var stock2={
    code:'000001.SZ',
    start_date:'20190701',
    end_date:'20190705',
}

// fastify.get('/get', async (request, reply) => {
//     console.log('-----------',request.query.stock);
//     tushare.post(stock.code,stock.start_date,stock.end_date,function(obj){
//       // console.log(obj)
//       reply.send(JSON.stringify(obj))
//     })
// })

fastify.route({
  method: ['POST','GET'],
  url: '/version',
  handler: function(request, reply){
    reply.send({v: cfg.version})
  }
})

fastify.route({
  method: ['GET'],
  url: '/quant',
  handler: function(request, reply){
    console.log(request.query,typeof(request.query));
    // reply.send({hello: 'world'})
    if(request.query && request.query.length > 0){
      var stock = JSON.parse(request.query.s)
      console.log(stock.code,stock.start_date,stock.end_date);  
      tushare.post(stock.code,stock.start_date,stock.end_date,function(obj){
          // console.log(obj)
          reply.send(JSON.stringify(obj))
      })
    }else{
      reply.send({error: 'params err'})
    }

    // "Access-Control-Allow-Origin：*
    // reply.send({hello: request.query})
  }
})

fastify.route({
  method: ['POST'],
  url: '/quant2',
  handler: function(request, reply){
    // console.log(request.body,'-',typeof(request.body));
    // reply.send({hello: 'world'})
    if(request.body.code.length > 0){
      var stock = request.body
      // console.log(stock.code,stock.start_date,stock.end_date);  
      tushare.post(stock.code,stock.start_date,stock.end_date,function(obj){
          // console.log(obj)
          conv.do(obj)
          // reply.send(JSON.stringify(obj))
          reply.send(obj)
      })
    }else{
      reply.send({error: 'params err'})
    }

    // "Access-Control-Allow-Origin：*

  }
})

mongo.get(function(err,db){
    // console.log(err,db)
    mongo.release(db)
})

const start = async () => {
  try {
    await fastify.listen(cfg.port)
    fastify.log.info('server listening on ${fastify.server.address().port}')
    console.log('web is listening :',cfg.port)
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start();